<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.orderCode"
        placeholder="审批单编号"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="btnQuery"
      />
      <el-input
        v-model="listQuery.materialCode"
        placeholder="物料编码"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="btnQuery"
      />
      <el-input
        v-model="listQuery.materialName"
        placeholder="设备名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="btnQuery"
      />
      <el-input
        v-model="listQuery.materialSpecification"
        placeholder="设备规格"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="btnQuery"
      />
      <el-input
        v-model="listQuery.supplierName"
        placeholder="供应商"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="btnQuery"
      />
      <el-input
        v-model="listQuery.contractCode"
        placeholder="合同编号"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="btnQuery"
      />
      <el-input
        v-model="listQuery.orderState"
        placeholder="状态"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="btnQuery"
      />
      <el-select v-model="listQuery.hasAttachment" clearable placeholder="有无附件">
        <el-option v-for="item in hasAttachmentOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-dropdown split-button type="primary" class="filter-item" @click="btnQuery">
        <i class="el-icon-search el-icon--left" />查询
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item icon="el-icon-zoom-out" @click.native="btnReset">重置</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button-group style="float: right;">
        <el-button
          v-permission="'purchase:order:save'"
          icon="el-icon-plus"
          type="primary"
          class="filter-item"
          @click="btnCreate"
        >新增
        </el-button>
        <el-button
          v-permission="'purchase:order:delete'"
          icon="el-icon-delete"
          class="filter-item"
          @click="btnDelete()"
        >批量删除
        </el-button>
        <el-upload
          style="float: left;"
          :show-file-list="false"
          accept=".xls,.xlsx"
          :before-upload="beforeUpload"
          action=""
        >
          <el-button type="primary">导入</el-button>
          <!-- <div slot="tip" class="el-upload__tip">只能导入excel文件，且不超过20MB</div> -->
        </el-upload>
        <el-button type="success" @click="exportDetail()">批量导出</el-button>
      </el-button-group>

    </div>
    <el-table
      ref="multipleTable"
      :data="records"
      border
      fit
      :highlight-current-row="true"
      style="width: 100%;"
      :cell-style="{padding:'3px'}"
      :default-sort="{prop: 'orderDate', order: 'descending'}"
      @sort-change="sortChange"
      @selection-change="selectionChange"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column sortable="custom" label="审批单编号" prop="orderCode" align="center" width="150px">
        <template slot-scope="scope"><span>{{ scope.row.orderCode }}</span></template>
      </el-table-column>
      <el-table-column sortable="custom" label="审批单日期" prop="orderDate" align="center" width="200px">
        <template slot-scope="scope"><span>{{ scope.row.orderDate }}</span></template>
      </el-table-column>
      <el-table-column label="总价" sortable="custom" prop="price" align="center">
        <template slot-scope="scope"><span>{{ scope.row.price }}</span></template>
      </el-table-column>
      <el-table-column label="备注" prop="comment" align="center">
        <template slot-scope="scope"><span>{{ scope.row.comment }}</span></template>
      </el-table-column>
      <el-table-column label="状态" prop="orderState" align="center">
        <template slot-scope="scope"><span>{{ scope.row.orderState }}</span></template>
      </el-table-column>
      <el-table-column label="附件数量" prop="attachmentNum" align="center" width="50px">
        <template slot-scope="scope"><span style="white-space:pre-line">{{ scope.row.attachmentNum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120px">
        <template slot-scope="{row}">
          <el-button-group style="float: left;">
            <el-button type="text" @click.native="btnView(row)">查看</el-button>
            <el-button style="margin-left: 5px" type="text" @click.native="btnUpdate(row)">修改</el-button>
            <el-button
              v-permission="'purchase:order:delete'"
              style="margin-left: 5px"
              type="text"
              divided
              @click.native="btnDelete(row.id)"
            >删除
            </el-button>
            <el-button
              style="margin-left: 5px"
              type="text"
              divided
              @click.native="btnExport(row)"
            >导出
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :current.sync="listQuery.current"
      :size.sync="listQuery.size"
      @pagination="list"
    />

    <order-detail ref="orderDetailRef" :dialog-status="dialogStatus" @handleChild="handleChild" />

    <el-dialog title="" :visible.sync="dialogFormVisible" width="95%" :close-on-click-modal="true">

      <el-tabs v-model="activeName">
        <el-tab-pane label="审批单详情" name="first">
          <el-form
            ref="dataForm"
            :rules="rules"
            :model="temp"
            :disabled="dialogStatus==='view'"
            label-position="right"
            label-width="110px"
          >
            <!-- <el-form-item label="ID" prop="id"><el-input v-model="temp.id" :readonly="dialogStatus==='update'"/></el-form-item> -->
            <el-col :span="12">
              <el-form-item label="审批单编号" prop="orderCode">
                <el-input v-model="temp.orderCode" />
              </el-form-item>
            </el-col>
            <!--<el-col :span="12">-->
            <!--<el-form-item label="审批单名称" prop="orderName">-->
            <!--<el-input v-model="temp.orderName" />-->
            <!--</el-form-item>-->
            <!--</el-col>-->
            <el-col :span="12">
              <el-form-item label="审批单日期" prop="orderDate">
                <el-input v-model="temp.orderDate" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="总价" prop="price">
                <el-input v-model="temp.price" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="orderState">
                <el-input v-model="temp.orderState" />
              </el-form-item>
            </el-col>
            <el-form-item label="备注" prop="comment">
              <el-input v-model="temp.comment" />
            </el-form-item>
          </el-form>
          <el-table
            :data="orderDetail"
            :row-class-name="orderDetailRowClassName"
            :cell-class-name="cellRowClassName"
            :span-method="arraySpanMethod"
            border
            style="width: 100%"
          >
            <el-table-column label="序号" type="index" />
            <el-table-column prop="materialCode" label="设备编码" align="center" width="100px" />
            <el-table-column prop="materialName" label="设备名称" align="center" width="150px" />
            <el-table-column prop="materialSpecification" label="规格" align="center" width="100px" />
            <el-table-column prop="unit" label="单位" align="center" width="50px" />
            <el-table-column prop="materialNum" label="数量" align="center" width="50px" />
            <el-table-column prop="unitPrice" label="单价（元）" align="center" width="70px"/>
            <el-table-column prop="materialTotalPrice" label="总价（元）" align="center" width="80px" />
            <el-table-column prop="projectName" label="项目（用途）" align="center" />
            <el-table-column prop="indentCode" label="采购订单编号" align="center" width="80px" />
            <!--<el-table-column prop="contractCode" label="合同编号" align="center" width="80px" />-->
            <el-table-column label="合同编号" align="center" width="80px">
              <template slot-scope="{row}">
                <span>{{ row.contractCode }}</span>
                <el-button v-if="!isEmpty(row.contractCode)" type="text" @click.native="editContract(row)">编辑</el-button>
                <el-button v-else type="text" @click.native="btnGen(row)">合并订单</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="contractState" label="合同状态" align="center" />
            <el-table-column prop="supplierName" label="供应商" align="center" width="200px" />
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="附件" name="second">
          <file-list
            ref="orderFiles"
            :query-file-param="queryFileTemp"
          />
        </el-tab-pane>
      </el-tabs>

      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="dialogFormVisible = false">取消</el-button>
        <el-button
          v-if="dialogStatus!=='view'"
          icon="el-icon-check"
          type="primary"
          @click="dialogStatus==='create'?createData():updateData()"
        >确定
        </el-button>
      </div>
    </el-dialog>
    <contract-detail ref="contractDetailRef" :dialog-status="'update'" @handleChild="handleChild" />
    <el-dialog
      title="提示"
      :visible.sync="confirmDialogVisible"
      width="30%"
    >
      <span>确定删除</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="confirmDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doDelete()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="导出条件"
      :visible.sync="exportDetailVisible"
      width="30%"
    >
      <el-form>
        <el-form-item label="审批单开始日期" prop="price">
          <el-date-picker
            v-model="exportStartDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          />
        </el-form-item>

        <el-form-item label="审批单结束日期" prop="price">
          <el-date-picker
            v-model="exportEndDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="exportDetailVisible = false">取 消</el-button>
        <el-button type="primary" @click="doExportBatch()">确 定</el-button>
      </span>
    </el-dialog>

    <!--合并采购订单-->
    <gen-contract ref="genContractRef" @handleChild="handleChild" />
  </div>
</template>
<style>
    .el-table .warning-row {
        background: oldlace !important;
    }

    .el-table .success-row {
        background: #f0f9eb !important;
    }
</style>
<script>
import Pagination from '@/components/Pagination'
import { deleteAction, getAction, postAction, putAction, getFileAction } from '@/api/manage'
import { Message } from 'element-ui'
import fileList from '@/views/purchase/file/components/fileList'
import contractDetail from '@/views/purchase/contract/contractDetail'
import genContract from '@/views/purchase/contract/genContract'
import orderDetail from '@/views/purchase/order/orderDetail'

export default {
  name: 'PurchaseOrder',
  components: {
    fileList,
    Pagination,
    contractDetail,
    genContract,
    orderDetail
  },
  data() {
    return {
      contractCodeArr: undefined,
      indentCodeArr: undefined,
      projectNameArr: undefined,
      supplierNameArr: undefined,
      records: null,
      selectedRecords: [],
      queryFileTemp: {
        orderId: ''
      },
      total: 0,
      listQuery: {
        current: 1,
        size: 10,
        order: 'orderDate',
        asc: false,
        orderCode: undefined,
        orderName: undefined,
        orderUsage: undefined,
        orderState: undefined,
        supplierName: undefined,
        materialName: undefined,
        materialSpecification: undefined,
        materialCode: undefined,
        indentCode: undefined,
        hasAttachment: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      temp: {
        id: undefined,
        orderCode: '',
        orderName: '',
        orderDate: '',
        price: '',
        orderUsage: '',
        comment: '',
        orderState: '',
        attachmentNum: ''
      },
      orderDetail: [],
      rules: {
        id: [{
          required: true,
          message: '该项不能为空',
          trigger: 'change'
        }],
        orderCode: [{
          required: true,
          message: '该项不能为空',
          trigger: 'change'
        }],
        orderName: [{
          required: true,
          message: '该项不能为空',
          trigger: 'change'
        }]
      },
      activeName: 'first',
      confirmDialogVisible: false,
      deleteIds: [],
      hasAttachmentOptions: [{
        value: '1',
        label: '有附件'
      }, {
        value: '0',
        label: '无附件'
      }
      ],
      exportDetailVisible: false,
      exportStartDate: '',
      exportEndDate: ''
    }
  },
  beforeCreate() {

  },
  created() {
    this.list()
  },
  methods: {
    sortChange(order) {
      this.listQuery.order = order.prop
      this.listQuery.asc = order.order == null ? true : order.order.indexOf('asc') !== -1
      this.list()
    },
    btnGen(row) {
      this.$refs.genContractRef.show(row.orderId, row.supplierId, true)
    },
    editContract(row) {
      this.$refs.contractDetailRef.show(row.contractId)
    },
    orderDetailRowClassName({ row, rowIndex }) {
      // 把每一行的索引放进row
      row.index = rowIndex
    },
    list() {
      getAction('/purchase/order/list', this.listQuery).then(res => {
        const {
          data
        } = res
        this.records = data.records
        this.total = data.total
      })
    },
    listOrderDetail(orderId) {
      var param = { 'orderId': orderId || this.temp.id }
      getAction('/purchase/orderDetail/listBy', param).then(res => {
        const {
          data
        } = res
        this.orderDetail = data
        this.merage()
      })
    },
    btnQuery() {
      this.listQuery.current = 1
      this.list()
    },
    btnReset() {
      this.listQuery = {
        current: 1,
        size: 10,
        order: 'orderDate',
        asc: false,
        orderCode: undefined,
        orderName: undefined,
        orderUsage: undefined,
        orderState: undefined
      }
      this.list()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        orderCode: '',
        orderName: '',
        price: '',
        orderUsage: '',
        comment: '',
        orderState: ''
      }
    },
    btnView(row) {
      this.temp = Object.assign({}, row)
      // 查询detail
      const param = { 'orderId': this.temp.id }
      this.queryFileTemp.orderId = this.temp.id
      if (this.$refs.orderFiles !== undefined) {
        this.$refs.orderFiles.getlistFile()
      }
      getAction('/purchase/orderDetail/listBy', param).then(res => {
        const {
          data
        } = res
        this.orderDetail = data
        this.merage()
        this.dialogStatus = 'view'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    btnCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.$refs.orderDetailRef.show(this.temp, [])
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          postAction('/purchase/order/save', this.temp).then(({
            msg
          }) => {
            this.dialogFormVisible = false
            Message.success(msg)
            this.list()
          })
        }
      })
    },
    btnUpdate(row) {
      this.temp = Object.assign({}, row)
      // 查询detail
      var param = { 'orderId': this.temp.id }
      getAction('/purchase/orderDetail/listBy', param).then(res => {
        const {
          data
        } = res
        this.orderDetail = data
        this.dialogStatus = 'update'
        this.$refs.orderDetailRef.show(this.temp, this.orderDetail)
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          putAction('/purchase/order/update', this.temp).then(({
            msg
          }) => {
            this.dialogFormVisible = false
            Message.success(msg)
            this.list()
          })
        }
      })
    },
    btnDelete(id) {
      const ids = id ? [id] : this.selectedRecords.map(record => {
        return record.id
      })
      if (ids.length === 0) {
        Message.error('请选择要删除的记录')
        return
      }
      this.deleteIds = ids
      this.confirmDialogVisible = true
    },
    btnExport(row) {
      getFileAction('/purchase/order/export?orderId=' + row.id).then(res => {
        if (res.type === 'application/json') {
          const reader = new FileReader() // 创建读取文件对象
          reader.addEventListener('loadend', function() { //
            const resJson = JSON.parse(reader.result) // 返回的数据
            Message.error(resJson.msg)
          })
          reader.readAsText(res, 'utf-8') // 设置读取的数据以及返回的数据类型为utf-8
        } else {
          const doca = window.document.createElement('a')
          const url = window.URL.createObjectURL(res)

          doca.href = url
          doca.setAttribute('download', row.orderCode + '.xls')
          window.document.body.appendChild(doca)
          doca.click()
          window.document.body.removeChild(doca)
          window.URL.revokeObjectURL(url)
        }
      })
    },

    doDelete() {
      deleteAction('/purchase/order/delete', {
        ids: this.deleteIds.toString()
      }).then(({
        msg
      }) => {
        Message.success(msg)
        this.list()
      })
      this.confirmDialogVisible = false
    },
    selectionChange(selectedRecords) {
      this.selectedRecords = selectedRecords
    },
    beforeUpload(file) {
      const formData = new FormData()
      formData.append('file', file)
      postAction('/purchase/order/upload', formData)
        .then(({ msg }) => {
          Message.success(msg)
          this.list()
        })
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 12) {
        const row1 = this.supplierNameArr[rowIndex]
        const col1 = row1 > 0 ? 1 : 0
        return {
          rowspan: row1,
          colspan: col1
        }
      }
      if (columnIndex === 10 || columnIndex === 11) {
        const row1 = this.contractCodeArr[rowIndex]
        const col1 = row1 > 0 ? 1 : 0
        return {
          rowspan: row1,
          colspan: col1
        }
      }
      if (columnIndex === 9) {
        const row1 = this.indentCodeArr[rowIndex]
        const col1 = row1 > 0 ? 1 : 0
        return {
          rowspan: row1,
          colspan: col1
        }
      }
      if (columnIndex === 8) {
        const row1 = this.projectNameArr[rowIndex]
        const col1 = row1 > 0 ? 1 : 0
        return {
          rowspan: row1,
          colspan: col1
        }
      }
    },
    merage() {
      this.contractCodeArr = []
      this.indentCodeArr = []
      this.projectNameArr = []
      this.supplierNameArr = []
      let codePos = 0
      let projectPos = 0
      let supplierPos = 0
      let indentPos = 0
      for (let i = 0; i < this.orderDetail.length; i++) {
        if (i === 0) {
          this.contractCodeArr.push(1)
          this.projectNameArr.push(1)
          this.supplierNameArr.push(1)
          this.indentCodeArr.push(1)
        } else {
          if (this.orderDetail[i].contractCode === this.orderDetail[i - 1].contractCode) {
            this.contractCodeArr[codePos] += 1
            this.contractCodeArr.push(0)
          } else {
            this.contractCodeArr.push(1)
            codePos = i
          }
          if (this.orderDetail[i].projectName === this.orderDetail[i - 1].projectName) {
            this.projectNameArr[projectPos] += 1
            this.projectNameArr.push(0)
          } else {
            this.projectNameArr.push(1)
            projectPos = i
          }
          if (this.orderDetail[i].supplierName === this.orderDetail[i - 1].supplierName) {
            this.supplierNameArr[supplierPos] += 1
            this.supplierNameArr.push(0)
          } else {
            this.supplierNameArr.push(1)
            supplierPos = i
          }

          if (this.orderDetail[i].indentCode === this.orderDetail[i - 1].indentCode) {
            this.indentCodeArr[indentPos] += 1
            this.indentCodeArr.push(0)
          } else {
            this.indentCodeArr.push(1)
            indentPos = i
          }
        }
      }
    },
    cellRowClassName({ row, column, rowIndex, columnIndex }) {
      if (row[column.property] === '完成') {
        return 'success-row'
      } else if (row[column.property] === '已到合同') {
        return 'warning-row'
      }
      return ''
    },
    /**
     * 获取子组件信号处理回调
     * data --子组件回传参数
     */
    handleChild(data) {
      const fns = {
        contractUpdated() {
          this.listOrderDetail()
        },
        indentMerged() {
          this.listOrderDetail()
        },
        orderUpdated() {
          this.list()
        }
      }
      return fns[data.type] && fns[data.type].call(this)
    },
    exportDetail() {
      this.exportDetailVisible = true
    },
    doExportBatch() {
      const param = { 'startDate': this.exportStartDate, 'endDate': this.exportEndDate }

      getFileAction('/purchase/orderDetail/export', param).then(res => {
        if (res.type === 'application/json') {
          const reader = new FileReader() // 创建读取文件对象
          reader.addEventListener('loadend', function() { //
            const resJson = JSON.parse(reader.result) // 返回的数据
            Message.error(resJson.msg)
          })
          reader.readAsText(res, 'utf-8') // 设置读取的数据以及返回的数据类型为utf-8
        } else {
          this.exportDetailVisible = false
          this.exportStartDate = ''
          this.exportEndDate = ''
          const doca = window.document.createElement('a')
          const url = window.URL.createObjectURL(res)

          doca.href = url
          doca.setAttribute('download', '审批单详情.xls')
          window.document.body.appendChild(doca)
          doca.click()
          window.document.body.removeChild(doca)
          window.URL.revokeObjectURL(url)
        }
      })
    }

  }
}
</script>
